<template>
  <div class="user-orderlist">
    <div v-if="!wuliu">
      <mt-header title="我的订单">
        <router-link to="/user" slot="left">
          <mt-button icon="back"></mt-button>
        </router-link>
      </mt-header>
      <!-- <mt-search v-model="userSearch"></mt-search> -->
      <div class="selectDiv">
          <div v-for="(v,i) in selectText" :key="i" :class="[i==selectIndex ? 'selectItem selected' : 'selectItem']" @click="changeNavigation(i)">
          <span>{{v}}</span>
          <i class="icon iconfont icon-xiajiantou"></i>
          </div>
      </div>
      <div style="height:.01rem"></div>
      <mt-tab-container style="min-height:10.55rem;background: #eee;" v-model="selectIndex">
        <mt-tab-container-item :id="selectIndex">
          <div class="order-list-children"
            v-infinite-scroll="loadMore"
            infinite-scroll-disabled="isMoreLoading"
            infinite-scroll-distance="10"
            :infinite-scroll-immediate-check="true"
          >
            <div class="order-list-bro border-bottom" v-for="(item, index) of list" :key="index">
              <mt-cell class="border-bottom" :title="item.storeName" is-link>
                <span style="color: red">{{item.status}}</span>
              </mt-cell>
              <div class="order-list-sn"><b>订单号：</b>{{item.orderSn}}</div>
              <div class="order-list-item" v-for="goods of item.arrayItem" :key="goods.goodsId">
                <router-link :to="'/detail/' + goods.goodsId">
                  <img :src="goods.img" class="order-list-item-img" alt="">
                  <img v-if="!goods.img" src="static/img/user.jpg" class="order-list-item-img" alt="">
                </router-link>
                <div>
                  <p>{{goods.name}}</p>
                  <p v-show="goods.point" style="margin:.1rem 0">积分：{{goods.point}}</p>
                  <p style="color: red;font-size:.02rem;margin-top:0.1rem;width: 100%;display: inline-block;">￥{{goods.price}} X {{goods.quantity}}</p>
                </div>
              </div>
              <div class="order-list-div">共<b>{{item.totalQuantity}}</b>件商品 实付款： <strong>￥{{item.totalPrice}}</strong> <span v-show="item.totalPoint">+{{item.totalPoint}}</span></div>
              <div class="order-list-div" style="text-align: right"><b>下单时间：</b>{{item.createDate}}</div>
              <div style="text-align: right">
                &nbsp;
                <mt-button @click="handleClickWuliu(item.id, item.expressSn, item.shipperCode)" v-if="item.expressSn" size="small" type="danger" plain>物流</mt-button>
                <mt-button @click="handleClickFukuan(item.id)" v-if="item.statusCode === 0" size="small" type="danger" plain>去付款</mt-button>
                <mt-button @click="handleClickQuxiao(item.orderSn, index)" v-if="item.statusCode === 0" size="small" type="danger" plain>取消订单</mt-button>
                <mt-button @click="handleClickShouhuo(item.id, index)" v-if="item.statusCode === 2" size="small" type="danger" plain>收货</mt-button>
                <mt-button @click="handleClickShouhou(item.id, index)" v-if="item.statusCode === 3 || item.statusCode === 11" size="small" type="danger" plain>售后</mt-button>
                <mt-button @click="handleClickTuihuo(item.id, index)" v-if="item.statusCode === 1 || item.statusCode === 2 || item.statusCode === 3" size="small" type="danger" plain>退货</mt-button>
                <router-link :to="'/user-orderitem/' + item.id">
                <mt-button v-if="item.statusCode === 3" size="small" type="danger" plain>评价</mt-button>
                </router-link>
              </div>
            </div>
            <div class="loading-box tc" v-if="isLoading">
              <mt-spinner :size="40" type="fading-circle" class="loading-more"></mt-spinner>
              <span class="loading-more-txt">加载中...</span>
            </div>
            <div class="not-content" v-if="noMore">---暂无更多记录---</div>
          </div>
        </mt-tab-container-item>
        <!-- <mt-tab-container-item id="1">
          <div class="order-list-children">
            <div class="not-content">---暂无更多记录---</div>
          </div>
        </mt-tab-container-item> -->
      </mt-tab-container>
    </div>
    <div v-if="wuliu">
      <mt-header title="物流信息">
        <div @click="colseWuliu" slot="right">
          关闭
        </div>
      </mt-header>
      <timeline>
        <timeline-item v-for="(item,index) of wuliuInfo" :key="index">
          <h4 :class="index===0 ? 'recent' : ''">{{item.AcceptStation}}</h4>
          <p :class="index===0 ? 'recent' : ''">{{item.AcceptTime}}</p>
        </timeline-item>
      </timeline>
    </div>
  </div>
</template>

<script>
import { Toast, MessageBox } from 'mint-ui'
import { Timeline, TimelineItem } from 'vux'
import axios from 'axios'
export default {
  name: 'OrderList',
  components: {
    Timeline,
    TimelineItem
  },
  data () {
    return {
      // selectText: [{name: 'all', title: '全部'}, {name: 'fukuan', title: '待付款'}, {fahuo:'待发货'}, {shouhuo:'待收货'}, {pingjia:'待评价'}, {shouhuo:'售后中'}],
      wuliu: false,
      wuliuInfo: [],
      selectText: {
        all: '全部',
        fukuan: '待付款',
        fahuo: '待发货',
        shouhuo: '待收货',
        pingjia: '待评价',
        shouhou: '售后中'
      },
      selectIndex: 0,
      weiXin: {
        appId: '',
        timeStamp: '',
        nonceStr: '',
        packageWeixin: '',
        paySign: ''
      },
      userSearch: '',
      selected: '0',
      list: [],
      isLoading: false, // 加载中转菊花
      isMoreLoading: true, // 加载更多中
      noMore: false, // 是否还有更多
      pageInfo: { // 分页信息
        page: 1,
        pageSize: 5,
        total: 0, // 总条数
        totalPage: 1 // 总分页数
      }
    }
  },
  methods: {
    changeNavigation (index) { // 切换标签页
      this.isMoreLoading = true
      this.selectIndex = index
      this.pageInfo.page = 1 // 初始化
      this.pageInfo.totalPage = 1
      this.list = []
      this.noMore = false
      this.$router.push({ path: '/user-orderlist', query: { type: index } })
      this.getInfo()
    },
    getInfo (type) {
      var status = ''
      if (this.$route.query.type) {
        this.selectIndex = this.$route.query.type
      }
      if (this.selectIndex === 'all') {
        status = ''
      }
      if (this.selectIndex === 'fukuan') {
        status = 0
      }
      if (this.selectIndex === 'fahuo') {
        status = 1
      }
      if (this.selectIndex === 'shouhuo') {
        status = 2
      }
      if (this.selectIndex === 'pingjia') {
        status = 3
      }
      if (this.selectIndex === 'shouhou') {
        status = 12
      }
      axios.get('/meimai/interface/order/listSuborder', {
        params: {
          'memberId': this.$store.state.userId,
          'status': status,
          'pageSize': this.pageInfo.pageSize,
          'page': this.pageInfo.page
        }
      }).then((res) => {
        let datas = res.data
        console.log(datas)
        if (datas.code === 0) {
          if (type === 'loadMore') {
            this.list = this.list.concat(datas.datas)
          } else {
            this.list = datas.datas
          }
          this.pageInfo.total = datas.total
          this.pageInfo.totalPage = datas.totalPage
        }
        this.isLoading = false
        this.isMoreLoading = false
      })
    },
    loadMore () {
      this.pageInfo.page += 1 // 增加分页
      this.isMoreLoading = true // 设置加载更多中
      this.isLoading = true // 加载中
      if (this.pageInfo.page > this.pageInfo.totalPage) { // 超过了分页
        this.noMore = true // 显示没有更多了
        this.isLoading = false // 关闭加载中
        return false
      }
      // 做个缓冲
      setTimeout(() => {
        this.getInfo('loadMore')
      }, 500)
    },
    handleClickQuxiao (data, index) {
      MessageBox.confirm('确定删除此订单?').then(action => {
        axios.get('/meimai/interface/order/cancleOrder', {
          params: {
            memberId: this.$store.state.userId,
            orderSn: data
          }
        }).then((res) => {
          // console.log(data)
          // console.log(res)
          let datas = res.data
          if (datas.code === 0) {
            Toast('删除成功')
            this.list.splice(index, 1)
            this.$router.push('/user-orderlist?type=fukuan')
          } else {
            Toast(datas.msg)
          }
        })
      })
    },
    isWeixinBrowser () {
      let ua = navigator.userAgent.toLowerCase()
      return !!(/micromessenger/.test(ua))
    },
    handleClickFukuan (data) {
      let wxPayType = ''
      if (this.isWeixinBrowser()) {
        wxPayType = 'JSAPI'
      } else {
        wxPayType = 'MWEB'
      }
      axios.get('/meimai/interface/order/orderPay', {
        params: {
          memberId: this.$store.state.userId,
          orderId: data,
          wxPayType: wxPayType
        }
      }).then((res) => {
        let datas = res.data
        if (datas.code === 0) {
          if (datas.type === 4 || datas.type === 1) {
            // this.$router.push(res.data.payUrl)
            // console.log(res)
            if (res.data.code === 0) {
              // console.log(res)
              Toast('支付成功')
              this.$router.push('/user')
            } else {
              Toast(datas.msg)
              this.$router.push('/cart')
            }
          }
          if (datas.type === 2) {
            if (this.isWeixinBrowser()) {
              this.weiXin.appId = res.data.appId
              this.weiXin.timeStamp = res.data.timeStamp
              this.weiXin.nonceStr = res.data.nonceStr
              this.weiXin.packageWeixin = res.data.package
              this.weiXin.paySign = res.data.paySign
              if (typeof WeixinJSBridge === 'undefined') {
                if (document.addEventListener) {
                  document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false)
                } else if (document.attachEvent) {
                  document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
                  document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
                }
              } else {
                this.onBridgeReady()
              }
            } else {
              window.location.href = res.data.payUrl
            }
          }
          if (datas.type === 3) {
            const div = document.createElement('div') // 创建div
            div.innerHTML = datas.payUrl // 将返回的form 放入div
            document.body.appendChild(div)
            document.forms[0].submit()
          }
        } else {
          Toast(datas.msg)
        }
      })
    },
    onBridgeReady (appId, timeStamp, nonceStr, packageWexin, paySign) {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          'appId': this.weiXin.appId, // 公众号名称，由商户传入
          'timeStamp': this.weiXin.timeStamp, // 时间戳，自1970年以来的秒数
          'nonceStr': this.weiXin.nonceStr, // 随机串
          'package': this.weiXin.packageWeixin,
          'signType': 'MD5', // 微信签名方式
          'paySign': this.weiXin.paySign // 微信签名
        },
        function (res) {
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            Toast('支付成功')
          } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
            Toast('取消支付')
          } else {
            Toast('支付失败')
          }
        }
      )
    },
    handleClickShouhuo (data, index) {
      axios.get('/meimai/interface/order/confirmReceipt', {
        params: {
          memberId: this.$store.state.userId,
          orderId: data
        }
      }).then((res) => {
        // console.log(res)
        let datas = res.data
        if (datas.code === 0) {
          Toast('操作成功')
          this.list.splice(index, 1)
        } else {
          Toast(datas.msg)
        }
      })
    },
    handleClickShouhou (data, index) {
      MessageBox.prompt('请填写售后原因').then(({ value, action }) => {
        axios.get('/meimai/interface/order/afterSale', {
          params: {
            memberId: this.$store.state.userId,
            orderId: data,
            message: value
          }
        }).then((res) => {
          // console.log(res)
          let datas = res.data
          if (datas.code === 0) {
            Toast('操作成功')
            this.list.splice(index, 1)
          } else {
            Toast(datas.msg)
          }
        })
      })
    },
    handleClickTuihuo (data, index) {
      MessageBox.prompt('请填写退款原因').then(({ value, action }) => {
        axios.get('/meimai/interface/order/returnGoods', {
          params: {
            memberId: this.$store.state.userId,
            orderId: data,
            message: value
          }
        }).then((res) => {
          // console.log(res)
          let datas = res.data
          if (datas.code === 0) {
            Toast('操作成功')
            this.list.splice(index, 1)
          } else {
            Toast(datas.msg)
          }
        })
      })
    },
    handleClickWuliu (id, expressSn, shipperCode) {
      this.wuliu = true
      axios.get('/meimai/interface/order/getExpressInfo', {
        params: {
          id: id,
          expressSn: expressSn,
          shipperCode: shipperCode
        }
      }).then((res) => {
        console.log(res)
        this.wuliuInfo = res.data.array.reverse()
      })
    },
    colseWuliu () {
      this.wuliu = false
    }
  },
  mounted () {
    this.getInfo()
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/mixins.styl'
@import '~styles/varibles.styl'
.recent
  color: #09BB07
.user-orderlist >>> .vux-timeline-item-content p
{
  margin: .2rem 0
}
b
  font-weight: bold
.mint-button--small
  height: .48rem
  margin-right: .15rem
  margin-bottom: .3rem
.user-orderlist >>> .mint-search
  height: auto
.user-orderlist >>> .mint-searchbar
  background: #fff
.user-orderlist >>> .mint-searchbar-inner, .user-orderlist >>> .mint-searchbar-core
  background: #e9e9e9
.user-orderlist >>> .mint-searchbar-cancel
  color: #1c1f20
.user-orderlist >>> .mint-navbar .mint-tab-item.is-selected
  border-bottom: .04rem solid #ec2935
  color: #ec2935
.user-orderlist >>> .mint-navbar
  border-bottom: 1px solid #eee
.user-orderlist >>> .mint-tab-item,
.user-orderlist >>> .mint-tab-item a
  color: #888
.mint-header
  background: $colorRed
.order-list-children
  .not-content
    margin: .2rem 0 1rem
    text-align: center
    width: 100%
    text-align: center
    color: #999
.order-list-bro
  background: #fff
  margin-top: .3rem
  .order-list-item
    display: flex
    align-items: center
    padding: .1rem
    color: #888
    .order-list-item-img
      width: 1.8rem
      height: 1.8rem
      margin-right: .05rem
  .order-list-sn
    margin: .2rem 0 .2rem .2rem
  .order-list-div
    text-align: right
    margin-right: .2rem
    margin-bottom: .2rem
    strong
      font-weight: 700
      font-size: .35rem
.selectDiv
  width: 100%
  display: flex
  align-items: center
  justify-content: center
  .selectItem
    height: 1.1rem
    display: flex
    align-items: center
    justify-content: center
    flex-direction: column
    box-sizing: border-box
    width: 20%
    color: #888
    .iconfont
      margin-top: 0.2rem;
      font-size: 0.3rem;
  .selected
    color: #ec2935
    border-bottom: 0.04rem solid #ec2935
</style>
